package com.innerchic.weqiuqiu.ui;

import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.core.app.RemoteInput;
import androidx.recyclerview.widget.RecyclerView;

import com.innerchic.annotations.base.ActivitySetting;
import com.innerchic.annotations.base.BindActivityLayoutHolder;
import com.innerchic.mapper.app.SuperActivity;
import com.innerchic.mapper.app.SuperAdapter;
import com.innerchic.sponsor.other.Subject;
import com.innerchic.weqiuqiu.R;
import com.innerchic.weqiuqiu.adapter.MessageAdapter;
import com.innerchic.weqiuqiu.bean.old.MessageMade;
import com.innerchic.weqiuqiu.bean.ServiceStatus;
import com.innerchic.weqiuqiu.emoji.Expression;
import com.innerchic.weqiuqiu.emoji.OnClickEmojiListener;
import com.innerchic.weqiuqiu.service.old.WeCoreService;
import com.innerchic.weqiuqiu.utils.NotificationUtils;

/**
 * ================================================
 * 作    者：贾恒飞 >>> 17515250730@163.com
 * 项    目：wedudu
 * 日    期：2022/1/11 15:17
 * 包    名：com.innerchic.wedudu
 * 描    述：
 * Create by zFox from AndroidStudio4.2
 * ================================================
 */
@BindActivityLayoutHolder
@ActivitySetting(layout = "activity_main", modificationActionBar = false, observer = true, backTows = true)
public class MainActivity extends SuperActivity implements SuperAdapter.OnItemMonitorListener<MessageMade> {

    private MainActivityLayoutHolder holder;

    private MessageAdapter messageAdapter;

    // 空白高度 = 屏幕高度 - 当前 Activity 的可见区域的高度
    // 当 blankHeight 不为 0 即为软键盘高度。
    private int blankHeight = 0;

    private static boolean showTop = false;

    @Override
    public void create() {
        //检查权限
        boolean listenersEnabled = NotificationUtils.isNotificationListenersEnabled(this);
        if (listenersEnabled) {
            NotificationUtils.toggleNotificationListenerService(this, WeCoreService.class);
        } else {
            showToast("尚未开启服务,请检测并打开服务");
        }

        messageAdapter = new MessageAdapter();
        messageAdapter.setItemMonitorListener(this);
        RecyclerView.LayoutManager layoutManager = messageAdapter.getLayoutManager();
        holder.recyclerView.setLayoutManager(layoutManager);
        holder.recyclerView.setAnimation(getRecyclerAnim().getAnimation());
        messageAdapter.bindRecyclerView(holder.recyclerView, this);

        boolean startService = WeCoreService.isStartService();
        cutService(startService);

        holder.serviceStatus.setOnClickListener(v -> {
            if (WeCoreService.isStartService()) {
                return;
            }
            resetPros();
        });

        //发送监听
        holder.sendBtn.setOnClickListener(v -> {
            if (messageMade == null) {
                showSnack(holder.buttonPanel, "请先选择一个对象回复.");
                return;
            }
            Editable text = holder.edtextContent.getText();
            if (text == null) {
                showSnack(holder.buttonPanel, "请输入回复内容.");
                return;
            }
            String message = text.toString();
            if ("".equals(message)) {
                showSnack(holder.buttonPanel, "请输入回复内容.");
                return;
            }
            holder.edtextContent.setText("");
            sendMessage(messageMade, message);
        });

        holder.expressionBtn.setOnClickListener(v -> {
            if (holder.emojiView.getVisibility() == View.VISIBLE) {
                showTop = false;
                holder.emojiView.setVisibility(View.GONE);
            } else {
                showTop = true;
                holder.emojiView.setVisibility(View.VISIBLE);
            }
        });

        holder.emojiView.setEmojiListener(new OnClickEmojiListener() {
            @Override
            public void onClick(Expression expression, int pos) {
                Editable text = holder.edtextContent.getText();
                if (text == null || "".equals(text.toString())) {
                    holder.edtextContent.append("[" + expression.getName() + "]");
                    return;
                }
                int index = holder.edtextContent.getSelectionStart();
                text.insert(index, "[" + expression.getName() + "]");
            }

            @Override
            public void onLongClick(Expression expression, int pos) {
                showToast(expression.getName());
            }
        });
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_check) {
            //检查权限
            resetPros();
        }
        return super.onOptionsItemSelected(item);
    }

    private void resetPros() {
        boolean listenersEnabled = NotificationUtils.isNotificationListenersEnabled(this);
        if (listenersEnabled) {
            showToast("当前服务已开启.");
            NotificationUtils.toggleNotificationListenerService(this, WeCoreService.class);
        } else {
            boolean b = NotificationUtils.gotoNotificationAccessSetting(this);
            if (!b) {
                showToast("打开通知使用权设置页面失败,请手动前往'设置>应用'中设置.");
            }
        }
    }

    @Subject(thread = Subject.THREAD_MAIN)
    private void onMessage(MessageMade made) {
        messageAdapter.appendAndRefreshData(made);
    }

    @Subject(thread = Subject.THREAD_MAIN)
    private void onServiceStatus(ServiceStatus serviceStatus) {
        boolean serviceIsOpen = serviceStatus.isServiceIsOpen();
        cutService(serviceIsOpen);
    }

    private void cutService(boolean serviceIsOpen) {
        if (serviceIsOpen) {
            holder.serviceStatus
                    .setText("当前服务已开启");
            holder.serviceStatus.setBackgroundColor(getResources().getColor(R.color.icon_green));
        } else {
            holder.serviceStatus
                    .setText("当前服务未开启");
            holder.serviceStatus.setBackgroundColor(getResources().getColor(R.color.icon_rad));
        }
    }

    private MessageMade messageMade;

    @Override
    public void onMonitor(View monitorView, MessageMade data, int position, int type) {
        if (type == 1) {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                startIntentSender(data.getPendingIntent().getIntentSender(), intent, Intent.FLAG_ACTIVITY_NEW_TASK,
                        Intent.FLAG_ACTIVITY_NEW_TASK, 0);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
                showToast("启动异常,当前消息无法打开..");
            }
        } else if (type == 2) {
            String title = data.getTitle();
            String hint = "回复给:" + title;
            holder.edtextContent.setHint(hint);
            this.messageMade = data;
        }
    }

    private void sendMessage(MessageMade data, String message) {
        Intent localIntent = new Intent();
        Bundle resultBundle = new Bundle();
        resultBundle.putString(data.getResultKey(), message);
        RemoteInput.addResultsToIntent(new RemoteInput[]{new RemoteInput.Builder(data.getResultKey()).build()}, localIntent, resultBundle);
        try {
            data.getResultPendingIntent().send(getBaseContext(), 0, localIntent);
        } catch (Exception e) {
            showToast("该消息异常无法回复.");
        }
    }

}
